package cc.abanlee.framework.security.config;

import cc.abanlee.framework.security.core.filter.TokenAuthenticationFilter;
import cc.abanlee.framework.security.core.service.CustomUserDetailsService;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import java.util.Map;
import java.util.Set;

/**
 * @author: create by
 * @version: v1.0
 * @description:
 * @date:2022/8/17
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class LiWebSecurityAutoConfigurerAdapter extends WebSecurityConfigurerAdapter {

    @Resource
    private CustomUserDetailsService userDetailsService;
    @Resource
    private AuthenticationEntryPoint authenticationEntryPoint;
    @Resource
    private TokenAuthenticationFilter tokenAuthenticationFilter;
    @Resource
    private AccessDeniedHandler accessDeniedHandler;
    @Resource
    private ApplicationContext applicationContext;
    /**
     * Spring Security 加密器
     * 考虑到安全性，这里采用 BCryptPasswordEncoder 加密器
     *
     * @see <a href="http://stackabuse.com/password-encoding-with-spring-security/">Password Encoding with Spring Security</a>
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        // 获得 @PermitAll 带来的 URL 列表，免登录
        Multimap<HttpMethod, String> permitAllUrls = getPermitAllUrlsFromAnnotations();

        http.authorizeRequests()
//                .antMatchers("/system/auth/login")
//                .permitAll()  //指定URL无需保护
                .antMatchers(HttpMethod.GET,permitAllUrls.get(HttpMethod.GET).toArray(new String[0])).permitAll()
                .antMatchers(HttpMethod.POST,permitAllUrls.get(HttpMethod.POST).toArray(new String[0])).permitAll()
                .anyRequest() //其他请求
                .authenticated() //需要认证
//                .and()
//                .formLogin()
//                .and()
//                .csrf().disable()
                ;

        // 开启跨域
                http.cors().and()
                // CSRF 禁用，因为不使用 Session
                .csrf().disable();
        //把token校验过滤器添加到过滤器链中
        http.addFilterBefore(tokenAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

        //配置异常处理
        http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint)
        .accessDeniedHandler(accessDeniedHandler);
    }

    /**
     * 配置授权信息
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        userDetailsService.setPasswordEncoder(passwordEncoder());
        auth.userDetailsService(userDetailsService)
                .passwordEncoder(passwordEncoder());
    }


    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }


    private Multimap<HttpMethod, String> getPermitAllUrlsFromAnnotations(){

        Multimap<HttpMethod, String> result = HashMultimap.create();
        // 获得接口对应的 HandlerMethod 集合
        RequestMappingHandlerMapping requestMappingHandlerMapping = (RequestMappingHandlerMapping)
                applicationContext.getBean("requestMappingHandlerMapping");

        Map<RequestMappingInfo, HandlerMethod> handlerMethodMap = requestMappingHandlerMapping.getHandlerMethods();
        // 获得有 @PermitAll 注解的接口

        for(Map.Entry<RequestMappingInfo,HandlerMethod> entry: handlerMethodMap.entrySet()){
            HandlerMethod handlerMethod = entry.getValue();
            if(!handlerMethod.hasMethodAnnotation(PermitAll.class)){
                continue;
            }

            if(entry.getKey().getPatternsCondition()==null){
                continue;
            }

            Set<String> urls = entry.getKey().getPatternsCondition().getPatterns();

            // 根据请求方法，添加到 result 结果
            entry.getKey().getMethodsCondition().getMethods().forEach(requestMethod -> {
                switch (requestMethod) {
                    case GET:
                        result.putAll(HttpMethod.GET, urls);
                        break;
                    case POST:
                        result.putAll(HttpMethod.POST, urls);
                        break;
                    case PUT:
                        result.putAll(HttpMethod.PUT, urls);
                        break;
                    case DELETE:
                        result.putAll(HttpMethod.DELETE, urls);
                        break;
                }
            });
        }

        return result;
    }
}
